"""
AI对话框配置数据库模型
"""

from datetime import datetime
from typing import Optional, Dict, Any, List

from sqlalchemy import String, JSON, Integer, DateTime, ForeignKey, CheckConstraint
from sqlalchemy.orm import relationship, Mapped, mapped_column
from sqlalchemy.sql import func

from config.database import Base


class AIWebDialogModel(Base):
    """AI对话框配置数据库模型"""
    __tablename__ = "ai_web_dialog"

    # 主键
    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True, comment="主键ID")

    # 外键关联场景
    scene_id: Mapped[str] = mapped_column(
        String(50),
        ForeignKey("ai_web_scene.scene_id", ondelete="CASCADE"),
        nullable=False,
        comment="场景ID"
    )

    # 关联的Agent ID集合
    agent_ids: Mapped[Optional[str]] = mapped_column(
        String(200),
        nullable=True,
        comment="关联的Agent ID集合，多个ID用逗号分隔"
    )

    # 对话框配置字段
    dialog_size: Mapped[Dict[str, Any]] = mapped_column(JSON, nullable=False, comment="对话框尺寸配置（长、宽）")
    buttons: Mapped[List[Dict[str, Any]]] = mapped_column(JSON, nullable=False, comment="按钮集合配置")
    interactive_mode: Mapped[int] = mapped_column(Integer, nullable=False,
                                                  comment="交互模式(1=对话框,2=语音通话,3=视频聊天)")
    transparency: Mapped[int] = mapped_column(Integer, nullable=False, default=100, comment="对话框透明度（0-100）")

    # 时间戳字段
    created_time: Mapped[datetime] = mapped_column(
        DateTime,
        default=func.now(),
        nullable=False,
        comment="创建时间"
    )
    updated_time: Mapped[datetime] = mapped_column(
        DateTime,
        default=func.now(),
        onupdate=func.now(),
        nullable=False,
        comment="更新时间"
    )

    # 关系定义
    scene: Mapped["AIWebSceneModel"] = relationship(
        "AIWebSceneModel",
        back_populates="dialogs"
    )

    # 表约束
    __table_args__ = (
        CheckConstraint('transparency BETWEEN 0 AND 100', name='check_transparency_range'),
        {"comment": "AI Web对话框配置表"}
    )

    def __repr__(self):
        return f"<AIWebDialogModel(id={self.id}, scene_id='{self.scene_id}', transparency={self.transparency})>"

    def to_dict(self) -> dict:
        """转换为字典"""
        return {
            "id": self.id,
            "scene_id": self.scene_id,
            "agent_ids": self.agent_ids,
            "dialog_size": self.dialog_size,
            "buttons": self.buttons,
            "interactive_mode": self.interactive_mode,
            "transparency": self.transparency,
            "created_time": self.created_time.isoformat() if self.created_time else None,
            "updated_time": self.updated_time.isoformat() if self.updated_time else None
        }

    def validate_transparency(self) -> bool:
        """验证透明度值是否在有效范围内"""
        return 0 <= self.transparency <= 100

    def validate_dialog_size(self) -> bool:
        """验证对话框尺寸配置是否有效"""
        if not isinstance(self.dialog_size, dict):
            return False

        required_keys = ['width', 'height']
        return all(key in self.dialog_size for key in required_keys)

    def validate_buttons(self) -> bool:
        """验证按钮配置是否有效"""
        if not isinstance(self.buttons, list):
            return False

        for button in self.buttons:
            if not isinstance(button, dict):
                return False
            # 检查按钮必需字段
            required_keys = ['id', 'text', 'type']
            if not all(key in button for key in required_keys):
                return False

        return True

    def validate_interactive_mode(self) -> bool:
        """验证交互模式配置是否有效"""
        return self.interactive_mode in [1, 2, 3]

    def is_valid_config(self) -> bool:
        """检查整个配置是否有效"""
        return (
                self.validate_transparency() and
                self.validate_dialog_size() and
                self.validate_buttons() and
                self.validate_interactive_mode()
        )

    def get_button_by_id(self, button_id: str) -> Optional[Dict[str, Any]]:
        """根据ID获取按钮配置"""
        for button in self.buttons:
            if button.get('id') == button_id:
                return button
        return None

    def add_button(self, button_config: Dict[str, Any]) -> bool:
        """添加按钮配置"""
        if not isinstance(button_config, dict):
            return False

        required_keys = ['id', 'text', 'type']
        if not all(key in button_config for key in required_keys):
            return False

        # 检查ID是否已存在
        if self.get_button_by_id(button_config['id']):
            return False

        self.buttons.append(button_config)
        return True

    def remove_button(self, button_id: str) -> bool:
        """移除按钮配置"""
        for i, button in enumerate(self.buttons):
            if button.get('id') == button_id:
                self.buttons.pop(i)
                return True
        return False

    def update_button(self, button_id: str, button_config: Dict[str, Any]) -> bool:
        """更新按钮配置"""
        for i, button in enumerate(self.buttons):
            if button.get('id') == button_id:
                self.buttons[i] = {**button, **button_config}
                return True
        return False

    def get_mode_name(self) -> str:
        """获取交互模式名称"""
        mode_names = {
            1: "对话框",
            2: "语音通话",
            3: "视频聊天"
        }
        return mode_names.get(self.interactive_mode, "未知模式")
